<!-- 邮件资源 -->
<template>
  <div> <!--   class="dashboard-editor-container" -->
    <el-row style="background: #fff;">
      <div class="content parameType" style="width: 100%" v-show="1 === 2">
        <div class="certification top"  style="width: 100%">
          <div class="toptitle">
            <div class="title">内部群发邮箱配置</div>
            <div class="tabclick"  @click="formshow = !formshow" >
              <div class="tabitem">
                <span><i :class="formshow ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i></span>
              </div>
            </div>
          </div>
          <el-form label-width="200px" v-show="formshow">
            <el-col :xs="24" :sm="24" :lg="24">
              <el-form-item label="发件人昵称:">
                <el-input v-model="emailForm.SendNickName" style="width:300px"></el-input>
              </el-form-item>
              <p>发件人显示昵称：<el-switch v-model="emailForm.IsAddCorpNameToSendAccount" active-color="#2491fc" inactive-color="#ccc" :active-value = 1 :inactive-value = 0></el-switch></p>
            </el-col>
            <el-col :xs="24" :sm="24" :lg="24">
              <el-form-item label="邮件推广执行时间点:">
                <el-select v-model="emailForm.ExecHours"  style="width:300px">
                  <el-option value=0 label="0"></el-option>
                  <el-option v-for="item in 24" :key="item" :value=item :label="item+':00'"></el-option>
                </el-select>
              </el-form-item>
              <p>（0表示不限制时间点，否则为配置的时间点执行）</p>
            </el-col>
            <el-col :xs="24" :sm="24" :lg="24">
              <el-form-item label="邮件发送延迟:">
                <el-input v-model="emailForm.SendInterval"  style="width:300px" oninput ="value=value.replace(/[^0-9]/g,'')" :maxlength="10"></el-input>
              </el-form-item>
              <p>（0表示不延迟，单位秒）</p>
            </el-col>
            <el-col :xs="24" :sm="24" :lg="24">
              <el-form-item label="每日最大发送邮件数量:">
                <el-input v-model="emailForm.MaxCountPerDay"  style="width:300px" oninput ="value=value.replace(/[^0-9]/g,'')" :maxlength="10"></el-input>
              </el-form-item>
              <p>（0表示限制，单位条数）</p>
            </el-col>
            <el-col :xs="24" :sm="24" :lg="24">
              <el-form-item label="普通邮件使用系统内置邮箱:">
                <el-switch v-model="emailForm.UseDefaultEMailAccount" active-color="#2491fc" inactive-color="#ccc" :active-value = 1 :inactive-value = 0></el-switch>
              </el-form-item>
              <p>（开启表示使用系统内置邮件服务器，否则自行指定下面邮箱）</p>
            </el-col>
            <el-col :xs="24" :sm="24" :lg="24">
              <el-form-item label="精准邮件使用系统内置邮箱:">
                <el-switch v-model="emailForm.UseDefaultEMailAccountExtra" active-color="#2491fc" inactive-color="#ccc" :active-value = 1 :inactive-value = 0></el-switch>
              </el-form-item>
              <p>（开启表示使用系统内置邮件服务器，否则自行指定下面邮箱）</p>
            </el-col>
            <el-col :xs="24" :sm="24" :lg="24">
              <el-form-item label="默认邮箱前缀:">
                <el-input v-model="emailForm.DefaultEMailAccountFormat"  style="width:300px" oninput="value=value.replace(/[\u4E00-\u9FA5]/g,'')" :maxlength="32"></el-input>
              </el-form-item>
              <p>（开启系统内置邮件服务器时指定发送邮箱前缀，比如：sales_qq）</p>
            </el-col>
            <el-col :xs="24" :sm="24" :lg="24">
              <el-form-item label="默认邮箱服务器:">
                <el-input v-model="emailForm.DefaultSMTPServer"  style="width:300px" oninput="value=value.replace(/[\u4E00-\u9FA5]/g,'')" :maxlength="32"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :lg="24">
              <el-form-item label="默认邮箱密码:">
                <el-input v-model="emailForm.DefaultEMailPwd"  style="width:300px" oninput="value=value.replace(/[\u4E00-\u9FA5]/g,'')" :maxlength="32"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :lg="24">
              <el-form-item label="默认邮箱开启加密机制:">
                <el-switch v-model="emailForm.DefaultEmailOpenSSL" active-color="#2491fc" inactive-color="#ccc" :active-value = 1 :inactive-value = 0></el-switch>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :lg="24">
              <el-button type="primary" @click="SetParamMailGlobal(emailForm)"  style="margin-left:670px">保存</el-button>
            </el-col>
          </el-form>
        </div>
      </div>
      <div class="parameType" style="margin-top:0">
      <div>
        <!-- <div class="title" >群发邮件共享资源（为了保证邮件能够正常发送，请尽可能多增加邮箱账号）</div> -->
        <!-- <div class="title" >群发邮件共享资源<span style="color:#F56C6C">（建议不配置，使用系统自动分配邮件服务器）</span></div> -->
      </div>
        <div class="btn">
          <div>
            <el-button type="primary" icon='el-icon-circle-plus-outline' @click="addResources()">添加资源</el-button>
            <el-button type="primary" icon='el-icon-finished' @click="importResources()">导入资源</el-button>
            <el-button type="primary" icon='el-icon-download' @click="DownloadFile()">下载模板</el-button>
            <el-button type="primary" icon='el-icon-magic-stick' @click="TestAllMailGlobal()" :loading=loading>测试全部账号</el-button>
            <input style="display:none" type="file" ref="upfile" @change="changefile($event)" accept=".xls,.xlsx">
          </div>
          <div style="display:flex;margin-left: 50px;" v-show="loading">
            <i class="el-icon-loading"></i>
            <div class="percentage">
              <el-progress :percentage="percentage" :stroke-width="10" :show-text=false></el-progress>
            </div>
          </div>
          <div style="display:flex;margin-left: 50px;" v-show="loadingtext">
            <p style="color: #aaa;">当前邮箱 <span style="color: #67C23A;">正常 {{correct}} 个</span>，<span style="color: #F56C6C;">异常 {{abnormal}} 个</span></p>
          </div>
        </div>
        <el-table stripe border :data="tableData" style="width: 100%; margin-top: 15px" height="650">
          <el-table-column label="序号"  width="60" type="index" :index='(index)=>{return (index + 1) + (this.pageNum - 1)*this.pageSize}'> </el-table-column>
          <el-table-column label="申请人员" prop="Name" align="left" width="100px" show-overflow-tooltip></el-table-column>
          <el-table-column label="邮箱" prop="Account" align="left" show-overflow-tooltip></el-table-column>
          <el-table-column label="健康度" prop="health" align="left" show-overflow-tooltip>
            <template slot-scope="{row}">
              <span style="color:#5fb87c;margin-right:5px;" v-if="row.SendSuccessCount">送达：{{ row.SendSuccessCount }}</span>
              <span style="color:#F56C6C;margin-right:5px;" v-if="row.SendFailCount">失败：{{ row.SendFailCount }}</span>
              <span style="color:#409EFF;margin-right:5px;" v-if="row.MailReadCount">已阅：{{ row.MailReadCount }}</span>
              <span style="color:#df5095;margin-right:5px;" v-if="row.MailFocusCount">关注：{{ row.MailFocusCount }}</span>
              <span style="color:#E6A23C;margin-right:5px;" v-if="row.MailRspCount">回复：{{ row.MailRspCount }}</span>
            </template>
          </el-table-column>
          <el-table-column label="密码" prop="Pwd" align="left" show-overflow-tooltip></el-table-column>
          <el-table-column label="发件服务器" prop="SmtpServer" align="left"  show-overflow-tooltip></el-table-column>
          <el-table-column label="发件加密" prop="IsSmtpOpenSSL" width="100" align="left"  show-overflow-tooltip></el-table-column>
          <el-table-column label="收件服务器" prop="ImapServer" align="left"  show-overflow-tooltip></el-table-column>
          <el-table-column label="收件加密" prop="IsImapOpenSSL"  width="100" align="left"  show-overflow-tooltip></el-table-column>
          <el-table-column label="每日发送邮件" prop="MaxCountPerDay" width="110"  show-overflow-tooltip>
            <template slot-scope="{row}">
              <span>{{ row.MaxCountPerDay - (row.LeftCount || 0) }}</span> / <span>{{row.MaxCountPerDay}}</span>
            </template>
          </el-table-column>
          <el-table-column label="最近测试时间" prop="LastCheckTime" align="left"  show-overflow-tooltip></el-table-column>
          <el-table-column label="状态" show-overflow-tooltip align="left" width="80px">
            <template slot-scope="scope">
              <p style="color:#909399" v-if="scope.row.Status === 0">初始</p>
              <p style="color:#67C23A" v-if="scope.row.Status === 1">正常</p>
              <p style="color:#F56C6C" v-if="scope.row.Status === 2">异常</p>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="220px">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="changeMailGlobal(scope.row)">修改</el-button>
              <el-button size="mini" type="danger" @click="deleteMailGlobal(scope.row)">删除</el-button>
              <el-button size="mini" type="success" @click="TestMailGlobal(scope.row,2)">测试</el-button>
            </template>
          </el-table-column>
        </el-table>
        </div>
    </el-row>
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape=false  
      :title="Action === 1 ? '添加资源' : '修改资源' "
      :visible.sync="dialogVisible"
      v-el-drag-dialog
      width="50%">
      <el-form label-width="170px" :model="resourceForm" :rules="rules" ref="resourceForm">
        <el-form-item label='申请人员:' prop="Name">
          <!-- <el-input v-model="resourceForm.Name" placeholder="请输入申请人员名称"></el-input> -->
          <el-select v-model="resourceForm.Name" placeholder="请输入申请人员名称" style="width: 100%">
            <el-option v-for="(item, index) in NameList" :key="index" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label='邮箱:' prop="Account">
          <el-input v-model="resourceForm.Account" placeholder="请输入邮箱" :disabled="Action === 2"></el-input>
        </el-form-item>
        <el-form-item label='密码:' prop="Pwd">
          <el-input v-model="resourceForm.Pwd" oninput="value=value.replace(/[\u4E00-\u9FA5 ]/g,'')" placeholder="请输入邮箱密码" :maxlength="32"></el-input>
        </el-form-item>
        <el-form-item label='邮件服务器:' prop="mailServer">
          <el-select v-model="resourceForm.mailServer" placeholder="请选择邮件服务器" style="width: 100%" @change="mailServerChange">
            <el-option v-for="(item, index) in sendmailServerList" :key="index" :label="item.serverName" :value="item.serverName"></el-option>
            <el-option label="其他" value="其他"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发件服务器:" prop="SmtpServer">
          <el-autocomplete class="inline-input" style="width: 80%"  @select="sendServerChange"  oninput="value=value.replace(/[\u4E00-\u9FA5 ]/g,'')" :maxlength="32" v-model="resourceForm.SmtpServer" :fetch-suggestions="querySearch" placeholder="请输入邮箱服务器">
            <template slot-scope="{ item }">
              <div class="name">{{ item.serverName }}</div>
              <span class="addr">{{ item.value }}</span>
            </template>
          </el-autocomplete>
          <el-checkbox style="width:10%;margin-left:10px;" v-model="resourceForm.IsSmtpOpenSSL" :true-label= 1 :false-label = 0>开启加密</el-checkbox>
        </el-form-item>
        <el-form-item label='收件服务器:' prop="ImapServer">
          <!-- <el-input style="width:80%" v-model="resourceForm.ImapServer" oninput="value=value.replace(/[\u4E00-\u9FA5 ]/g,'')" placeholder="请输入发件服务器" :maxlength="32"></el-input> -->
          <el-autocomplete class="inline-input" style="width: 80%" @select="collectServerChange"  oninput="value=value.replace(/[\u4E00-\u9FA5 ]/g,'')" :maxlength="32" v-model="resourceForm.ImapServer" :fetch-suggestions="querySearch3" placeholder="请输入发件服务器">
            <template slot-scope="{ item }">
              <div class="name">{{ item.serverName }}</div>
              <span class="addr">{{ item.value }}</span>
            </template>
          </el-autocomplete>
          <el-checkbox style="width:10%;margin-left:10px;" v-model="resourceForm.IsImapOpenSSL" :true-label= 1 :false-label = 0>开启加密</el-checkbox>
        </el-form-item>
        <el-form-item label='每日最大发送邮件数量:' prop="MaxCountPerDay">
          <el-input v-model.number="resourceForm.MaxCountPerDay" oninput="value=value.replace(/[^\d]/g,'')" placeholder="请输入每日最大发送邮件数量" :maxlength="32"></el-input>
        </el-form-item>
        <el-form-item label='状态:' prop="Status" v-show="Action !== 1">
          <span style="color: #909399" v-show="resourceForm.Status === 0">初始</span>
          <span style="color: #67C23A" v-show="resourceForm.Status === 1">正常</span>
          <span style="color: #F56C6C" v-show="resourceForm.Status === 2">异常</span>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit()">确 定</el-button>
        <el-button type="info" @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape=false
      title="请选择要导入的人员(已自动清除重复邮箱和错误邮箱)"
      ref="multipleTable"
      :visible.sync="importdialog"
      v-el-drag-dialog
      @close=importdialogclose
      width="70%">
      <el-table stripe border @selection-change="handleSelectionChange" :data="importList" height='500' style="width: 100%; margin-top: 15px;padding-bottom:15px;">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="序号"  width="60" type="index" :index='(index)=>{return (index + 1) + (this.pageNum - 1)*this.pageSize}'> </el-table-column>
        <el-table-column label="申请人员" prop="Name" align="left" width="120px"></el-table-column>
        <el-table-column label="邮箱" prop="Account" align="left"></el-table-column>
        <el-table-column label="密码" prop="Pwd" align="left"></el-table-column>
        <el-table-column label="发件服务器" prop="SmtpServer" align="left" ></el-table-column>
        <el-table-column label="开启发件服务器加密" prop="IsSmtpOpenSSL" align="left" ></el-table-column>
        <el-table-column label="收件服务器" prop="ImapServer" align="left"  show-overflow-tooltip></el-table-column>
        <el-table-column label="开启收件服务器加密" prop="IsImapOpenSSL" align="left"  show-overflow-tooltip></el-table-column>
        <el-table-column label="每日发送邮件" prop="MaxCountPerDay" width="110"  show-overflow-tooltip></el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitImport()">确认导入</el-button>
        <el-button type="info" @click="importdialog = false;">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { connrequest, downloadfile } from '@/api/firstPage'
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import XLSX from 'xlsx'
import { parseTime } from '@/utils'
import { load } from 'jszip/lib/object'
export default {
directives: { elDragDialog },
data() {
  return {
    isTestMail: true,
    correct: '',
    abnormal: '',
    percentage: 0,
    loading: false,
    loadingtext: false,
    pageNum: 1,
    pageSize: 10,
    total: 10,
    tableData: [],
    emailForm: {},
    emailList: [],
    importList:[],
    choseList:[],
    NameList: [],
    dialogVisible: false,
    importdialog: false,
    formshow:true,
    IsActivePwd: 0,
    rules: {
      Name:[
        { required: true, message: "请输入申请人员"},
      ],
      Account:[
        { required: true, message: "请输入邮箱"},
        {
          validator: function(rule, value, callback) {
            if (/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/i.test(value) == false  && value) {
              callback(new Error("邮箱格式错误"));
            } else {
              callback();
            }
          },
          trigger: "blur"
        }
      ],
      Pwd:[
        { required: true, message: "请输入密码"},
        {
          validator: function(rule, value, callback) {
            if (/^[^\u4e00-\u9fa5 ]{0,}$/.test(value) == false  && value) {
              callback(new Error("邮箱密码不能有中文或空格"));
            } else {
              callback();
            }
          },
          trigger: "blur"
        }
      ],
      mailServer: [
        { required: true, message: "请选择邮件服务器", trigger: "change"}
      ],
      SmtpServer:[
        { required: true, message: "请输入发件服务器"}
      ],
      ImapServer: [
        { required: true, message: "请输入收件服务器"}
      ],
      Status:[
        { required: true, message: "请选择状态"}
      ],
      MaxCountPerDay: [
        { required: true, message: "请输入每日最大发送邮件数量"}
      ]
    },
    resourceForm: {
      SmtpServer: '',
      ImapServer: '',
    },
    Action: 1,
    testmail:'',
    sendmailServerList: [],
    receivemailServerList: [],
  }
},
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.getData()
    this.GetEmployee()
    // this.GetParamMailGlobal()
    // this.GetEMailADTask()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    this.GetEMailSmtpCfg()
  },
  methods: {
    async GetEmployee(){
      const res = await connrequest('GetEmployee')
      let arr = []
      res.Data.map(item => {
        arr.push(item.Name)
      })
      this.NameList = arr
    },
    async GetEMailADTask(){
      const res = await connrequest('GetEMailADTask')
    },
    importResources(){
      this.$refs.upfile.click()
    },
    handleSelectionChange(val){
      this.choseList = val
    },
    AccountChange(row){
      let mail = row.split("@")[1]
      this.$set(this.emailForm, 'SmtpServer', this.emailList.find( item => item.Mail === mail)?.SmtpServer || '')
      this.emailchange(this.emailList.find( item => item.Mail === mail))
    },
    async GetEMailSmtpCfg(){
      let sendmailServerList = []
      let receivemailServerList = []
      const res = await connrequest('GetEMailSmtpCfg')
      res.Data = res.Data || []
      res.Data.map(item=>{
        item.value = item.SmtpServer
        sendmailServerList.push( {serverName: item.NickName, value: item.SmtpServer, IsImapOpenSSL: item.IsImapOpenSSL, IsOpenSSL: item.IsOpenSSL} )
        receivemailServerList.push( {serverName: item.NickName, value: item.ImapPop3Server, IsImapOpenSSL: item.IsImapOpenSSL, IsOpenSSL: item.IsOpenSSL} )
      })
      this.emailList = [...res.Data]
      this.sendmailServerList = sendmailServerList
      this.receivemailServerList = receivemailServerList
      let mail = this.emailForm.FromAccount ? this.emailForm.FromAccount.split("@")[1] : ''
      this.emailchange(this.emailList.find( item => item.Mail === mail))
    },
    async submitImport(){
      let success = 0
      let flag = 0;
      if(this.choseList.length === 0){
        this.$message.info('请先选择要导入的人员')
        return false
      }
      else{
        this.choseList.map(item=>{
          item.IsSmtpOpenSSL = item.IsSmtpOpenSSL === '加密' ? 1 : 0
          item.IsImapOpenSSL = item.IsImapOpenSSL === '加密' ? 1 : 0
          return item
        })
        const data = {
          Data: this.choseList
        }
        const res = await connrequest('ImportMailAccounts', data)
        if(res.Status.StatusCode === 0){
          this.$message.success('导入成功')
          this.importdialog = false
          this.$refs.upfile.value = ''
          this.getData()
        }
        // this.choseList.forEach(async(item) => {
        //   let Detail = item
        //   const data = {
        //     Data:{
        //       Action: 1,
        //       Detail: {
        //         ...Detail,
        //         Status: 0
        //       }
        //     }
        //   }
        //   const res = await connrequest('EditMailAccounts', data)
        //   flag++
        //   if(res.Status.StatusCode === 0){
        //     success++
        //   }
        //   if(flag === this.choseList.length){
        //     this.$message({
        //       showClose: true,
        //       duration: 7000,
        //       type: success == this.choseList.length ? 'success' : 'error',
        //       message: `导入成功${success}个，失败${this.choseList.length - success}个`
        //     });
        //     this.importdialog = false
        //     this.$refs.upfile.value = ''
        //     this.getData()
        //   }
        // })
      }
    },
    importdialogclose(){
      this.choseList = []
      this.$refs.upfile.value = ''
    },
    async DownloadFile(){
      const data = {
        Data:{
          FileName: '邮件资源模板.xlsx'
        }
      }
      const res = await downloadfile('DownloadPublicFile', data)
      let blobUrl = window.URL.createObjectURL(new Blob([res]));
      const a = document.createElement('a');
      a.style.display = 'none';
      a.download = '邮件资源模板.xlsx';
      a.href = blobUrl;
      a.click();
    },
    changefile(e){
      this.choseList = []
      // 读取表格文件
      let that = this;
      const files = e.target.files;
      if (files.length <= 0) {
        return false;
      } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
        this.$message({
          message: "上传格式不正确，请上传xls或者xlsx格式",
          type: "warning"
        });
        return false;
      } else {
        // 更新获取文件名
        that.upload_file = files[0].name;
      }
      const fileReader = new FileReader();
      fileReader.onload = ev => {
        try {
          const data = ev.target.result;
          const workbook = XLSX.read(data, {
            type: "binary"
          });
          const wsname = workbook.SheetNames[0]; //取第一张表
          const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]); //生成json表格内容
          this.da = [...ws]
          let arr = []
          this.da.map(v => {
            let obj = {}
            obj.Name = v['申请人员']
            obj.Account = v['邮箱']
            obj.Pwd = v['密码（需要开通SMTP一些邮件服务器需要为激活密码）']
            obj.SmtpServer = v['smtp服务器']
            obj.IsSmtpOpenSSL = v['是否加密（0：不加密，1：加密）']
            obj.ImapServer = v['imap服务器']
            obj.IsImapOpenSSL = v['imap_ssl加密']
            obj.MaxCountPerDay = v['每日最大邮件数量']
            arr.push(obj)
          })
          this.importList = [...arr]
          this.importList = this.unique(this.importList)  //删除exl的重复数据
          this.tableData.forEach(item => {  //删除和tableData重复数据
            this.importList = this.importList.filter(newitem => {
              return newitem.Account !== item.Account
            })
          })
          const email = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
          this.importList = this.importList.filter(item => {
            return email.test(item.Account)
          })
          this.importdialog = true
        } catch (e) {
          return false;
        }
      };
      fileReader.readAsBinaryString(files[0]);
    },
    unique(arr){
      var obj = {};
      var newArr = arr.reduce((prev,cur)=>{
        obj[cur.Account] ? '':obj[cur.Account] = true && prev.push(cur);
        return prev
      },[]);
      return newArr
    },
    mailServerChange(value){
      if(value === '其他'){
        this.resourceForm = {...this.resourceForm, SmtpServer: '', IsSmtpOpenSSL: 0, ImapServer: '', IsImapOpenSSL: 0}
      }else{
        let row = this.sendmailServerList.find(item =>  item.serverName === value)
        let row2 = this.receivemailServerList.find(item =>  item.serverName === value)
        this.resourceForm = {...this.resourceForm, SmtpServer: row.value, IsSmtpOpenSSL: row.IsOpenSSL, ImapServer: row2.value, IsImapOpenSSL: row.IsImapOpenSSL}
      }
    },
    sendServerChange(row){
      this.$set( this.resourceForm, 'IsSmtpOpenSSL', row.IsOpenSSL)
    },
    collectServerChange(row){
      this.$set( this.resourceForm, 'IsImapOpenSSL', row.IsImapOpenSSL)
    },
    querySearch(queryString, cb) {
      var restaurants = this.sendmailServerList;
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    querySearch3(queryString, cb) {
      var restaurants = this.receivemailServerList;
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    querySearch2(queryString, cb) {
      let arr = []
      for (var i = 1; i <= 24; i++){
        arr.push({value: `${i}:00`})
      }
      var restaurants = arr;
      var results = queryString ? restaurants.filter(this.createFilter2(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter2(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    emailchange(row){
      this.$set(this.emailForm, 'IsSmtpOpenSSL', row?.IsSmtpOpenSSL || 0)
      this.$set(this.emailForm, 'IsImapOpenSSL', row?.IsImapOpenSSL || 0)
      this.IsActivePwd = row?.IsActivePwd || 0
    },
    addResources(){
      this.Action = 1
      this.resourceForm = {...{Status: 0, IsSmtpOpenSSL:0, IsImapOpenSSL: 0}}
      this.$nextTick(()=>{
        this.$refs['resourceForm'].clearValidate()
      })
      this.dialogVisible = true
    },
    changeMailGlobal(row){
      this.dialogVisible = true
      let serve = this.sendmailServerList.find(item =>  item.value === row.SmtpServer)
      this.Action = 2
      this.resourceForm = {...row, mailServer: serve ? serve.serverName : '其他', IsSmtpOpenSSL: row.IsSmtpOpenSSL === '加密' ? 1 : 0, IsImapOpenSSL: row.IsImapOpenSSL === '加密' ? 1 : 0}
    },
    deleteMailGlobal(row){
      if (this.deletingMail) {
      return;
      }
      this.deletingMail = true;
      setTimeout(() => {
        this.deletingMail = false;
      },1000);
    // 设置1秒的定时器

      this.Action = 3
      this.resourceForm = {...row}
      this.$confirm('此操作将删除该邮箱, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const data = {
          Data:{
            Action: this.Action,
            Detail: {
              ...this.resourceForm
            }
          }
        }
        const res = await connrequest('EditMailAccounts', data)
        if(res.Status.StatusCode === 0){
          this.$message.success('删除成功')
          this.dialogVisible = false
          this.getData()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
    async GetParamMailGlobal(){
      const res = await connrequest('GetParamMailADGlobal')
      const testmail = await connrequest('GetParamMailGlobal')
      this.testmail = testmail.Data.ToAccount
      this.emailForm = {...res.Data}
    },
    async getData() {
      const res = await connrequest('GetParamMailAccounts')
      res.Data = res.Data || []
      res.Data.map( item =>{
        item.IsSmtpOpenSSL = item.IsSmtpOpenSSL === 1 ? '加密' : '不加密'
        item.IsImapOpenSSL = item.IsImapOpenSSL === 1 ? '加密' : '不加密'
        item.LastCheckTime = parseTime(item.LastCheckTime)
        return item
      })
      this.tableData = res.Data
    },
    async SetParamMailGlobal(){
      let SendInterval = /^[0-9]*$/ 
      let email = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
      let regPwd = /^[^\u4e00-\u9fa5 ]{0,}$/
      if(!SendInterval.test(this.emailForm.ExecHours) && this.emailForm.ExecHours* 1 > 24){
        this.$message.error('邮件推广执行时间点只能为小于24的数字')
      }
      else if(!SendInterval.test(this.emailForm.SendInterval)){
        this.$message.error('邮件发送延迟只能为数字')
      }else if(!SendInterval.test(this.emailForm.MaxCountPerDay)){
        this.$message.error('最大发送邮件数量只能为数字')
      }else if(this.emailForm.DefaultEMailAccountFormat === ''){
        this.$message.error('默认邮箱前缀不能为空')
      }else if(this.emailForm.DefaultSMTPServer === ''){
        this.$message.error('默认邮箱服务器不能为空')
      }else if(this.emailForm.DefaultEMailPwd === ''){
        this.$message.error('默认邮箱密码不能为空')
      }else if(!regPwd.test(this.emailForm.DefaultEMailPwd)){
        this.$message.error('默认邮箱密码不能有中文或空格')
      }else{
        this.emailForm.ExecHours = this.emailForm.ExecHours * 1
        this.emailForm.SendInterval = this.emailForm.SendInterval * 1 || 0
        this.emailForm.MaxCountPerDay = this.emailForm.MaxCountPerDay * 1 || 0
        const data = {
          Data:{
            ...this.emailForm
          }
        }
        const res = await connrequest('SetParamMailADGlobal', data)
        if(res.Status.StatusCode === 0){
          this.$message.success('保存成功')
          this.GetParamMailGlobal()
        }
      }
    },
    submit(){
      this.$refs['resourceForm'].validate(async (valid) => {
        if(valid){
          const data = {
            Data:{
              Action: this.Action,
              Detail: {
                ...this.resourceForm,
                MaxCountPerDay: this.resourceForm.MaxCountPerDay * 1 || 0,
                // IsSmtpOpenSSL: this.resourceForm.IsSmtpOpenSSL === '加密' ? 1 : 0,      
                // IsImapOpenSSL: this.resourceForm.IsImapOpenSSL === '加密' ? 1 : 0,        
              }
            }
          }
          const res = await connrequest('EditMailAccounts', data)
          if(res.Status.StatusCode === 0){
            this.Action === 1 ? this.$message.success('添加成功') : this.$message.success('修改成功')
            this.dialogVisible = false
            this.getData()
          }
        }
      })
    },
    async TestMailGlobal(row,status,flag = true){
      this.loadingtext = false
      // const loading = this.$loading({
      //   lock: true,
      //   text: "加载中……",
      //   background: "rgba(0, 0, 0, 0.7)",
      // });
      const ParamMailGlobal = await connrequest('GetParamMailGlobal')
      if(!ParamMailGlobal.Data.ToAccount){
        this.$message.error('发送测试邮箱失败，请在邮件通知->参数配置界面配置好接收邮箱再进行测试')
        return false
      }
      this.loading = true
      try{
      let IsSmtpOpenSSL
      let IsImapOpenSSL
      if(status === 1){
        IsSmtpOpenSSL = row.IsSmtpOpenSSL
        IsImapOpenSSL = row.IsImapOpenSSL
      }
      if(status === 2){
        IsSmtpOpenSSL = row.IsSmtpOpenSSL === '加密' ? 1 : 0
        IsImapOpenSSL = row.IsImapOpenSSL === '加密' ? 1 : 0
      }
      const data = {
        Data:{
          FromAccount: row.ToAccount || row.Account,
          Pwd: row.Pwd,
          SmtpServer: row.SmtpServer,
          ImapServer: row.ImapServer,
          IsSmtpOpenSSL: IsSmtpOpenSSL,
          IsImapOpenSSL: IsImapOpenSSL,
          IsAddCorpNameToSendAccount: this.emailForm.IsAddCorpNameToSendAccount,
          SendNickName: this.emailForm.SendNickName,
          ToAccount: ParamMailGlobal.Data.ToAccount
        },
        Header: {
          showLoading: flag
        }
      }
      const res = await connrequest('TestMailGlobal', data)
      if(res.Status.StatusCode === 0){
        this.correct++
        this.$message.success('发送测试邮件正常')
        // this.getData()
      }else{
        // this.abnormal++
        // this.$message.error('邮箱测试异常，发送测试邮件失败')
        // this.getData()
      }
      // loading.close()
      // this.abnormal = this.tableData.length - this.correct
      this.loading = false
      flag && this.getData()
      }catch(e){
      this.abnormal++
      this.getData()
      this.loading = false
        // loading.close()
      }
    },
    async TestAllMailGlobal(){
      this.percentage = 0
      const { tableData } = this
      this.loadingtext = false
      this.correct = 0
      this.abnormal = 0
      // const loading = this.$loading({
      //   lock: true,
      //   text: "加载中……",
      //   background: "rgba(0, 0, 0, 0.7)",
      // });
      let num = 100 / tableData.length
      for (let i = 0; i < tableData.length; i++) {
        if (!this.isTestMail) return
        await this.TestMailGlobal(tableData[i], 2, false)
        this.percentage = this.percentage + num
      }
      // loading.close()
      this.loadingtext = true
      this.getData()
    },
    handleSizeChange(){},
    handleCurrentChange(){}
  },
  beforeDestroy () {
    this.isTestMail = false
  }
}
</script>
<style lang="scss" scoped>
/* @import url(); 引入css类 */
@import "~@/styles/variables.scss";
.parameType .title{
  border: none !important;
}
.content {
  margin-top: 0;
  width: 800px;
  position: relative;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  .title{
    margin-bottom: 10px;
    border: none;
    cursor: pointer;
  }
  ::v-deep .certification{
    .toptitle{
      display: flex;
      // border-bottom: 1px solid #eceff5;
      // align-items: center;
      justify-content: space-between;
      // i{
      //   color: #409EFF;
      //   cursor: pointer;
      // }
    }
    .el-form-item{
      margin-bottom: 10px;
    }
    .el-col{
      display: flex;
      align-items: center;
      p{
        width: 100px;
        display:block;
        color: #aaa;
        font-size: 12px;
        padding-left: 20px;
        white-space: nowrap;
      }
    }
  }
}
.top{
  flex-wrap: nowrap;
}
.btn{
  margin: 20px 0;
  display: flex;
  align-items: center;
  .percentage{
    width: 350px;
    margin-left: 20px;
  }
}
.my-autocomplete {
  li {
    line-height: normal;
    padding: 7px;
    .name {
      text-overflow: ellipsis;
      overflow: hidden;
      line-height: 14px !important;
    }
    .addr {
      font-size: 12px;
      color: #b4b4b4;
    }
    .highlighted .addr {
      color: #ddd;
    }
  }
}

.tabclick{
  display: flex;
  height: 20px;
  margin-top: 0;
  justify-content: center;
  .tabitem{
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content:center;
    padding: 2px 10px;
    width: 90px;
    font-size: 12px;
    color: #bbb;
    border-radius: 4px;
    border: 1px solid #ebeef5;
    margin-right: 10px;
    transform:  perspective(2em) rotateX(-20deg);
    span{
      transform:  perspective(2em) rotateX(10deg);
    }
  }
}
.tabclick :hover{
  background: #f7f7f7;
}



</style>